# -*- coding: utf-8 -*-
import os
import PIL
import sys
import time
from PIL import Image
from StringIO import StringIO
from settings import *
from django.db import models
from django.contrib.auth.models import User
from dmblog.settings import MEDIA_ROOT
from django.db.models.fields.files import ImageFieldFile
from dmblog.utils import formatter


def make_thumb(im, size=150):

    width, height = im.size
    if width == height:
        region = im
    else:
        if width > height:
            delta = (width - height) / 2
            box = (delta, 0, delta + height, height)
        else:
            delta = (height - width) / 2
            box = (0, delta, width, delta + width)
        region = im.crop(box)

    thumb = region.resize((size, size), Image.ANTIALIAS)
    return thumb


def upload_avatar(data):
    state = {
        'success': False,
        'path': '',
    }
    try:
        base_im = Image.open(data)
    except Exception as e:
        state['success'] = False
        return state

    size50 = (50, 50)
    size150 = (150, 150)

    size_array = (size50, size150)

    # generate file name and the file path
    file_name = time.strftime('%Y%H%M%S') + '.jpeg'
    file_root_path = '%savatar/' % (MEDIA_ROOT)
    file_sub_path = '%s' % (str(time.strftime("%Y/%m/%d/")))

    # make different sizes photos
    for size in size_array:
        file_middle_path = '%d/' % size[0]

        file_path = os.path.abspath(
            file_root_path + file_middle_path + file_sub_path)

        im = base_im
        im = make_thumb(im, size[0])

        # check path exist
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        im.save('%s/%s' % (file_path, file_name), 'jpeg')

    state['success'] = True
    state['path'] = file_sub_path + file_name
    return state


# Area Model
class Area(models.Model):
    TYPE_CHOISES = (
        (0, u'未知'),
        (1, u'省'),
        (2, u'市'),
    )
    name = models.CharField(u'地名', max_length=100, default='未知')
    code = models.CharField(u'代码', max_length=255, default='0')
    types = models.IntegerField(u'类型', choices=TYPE_CHOISES, default='0')

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'地区'
        verbose_name_plural = u'地区'


# User model
class Profile(models.Model):

    user = models.OneToOneField(User)
    nickname = models.CharField(u'昵称', max_length=30, blank=True, default='')
    area = models.ForeignKey(Area, verbose_name=u'地区')

    avatar = models.ImageField(
        u'头像', upload_to='avatar/%Y/%m/%d',
        default='',
        blank=True
    )

    homepage = models.URLField(u'个人主页', max_length=200, default='', blank=True)
    about = models.TextField(u'关于我', max_length=1000, default='', blank=True)
    addtime = models.DateTimeField(u'注册时间', auto_now=True)

    def __unicode__(self):
        return self.user.username

    def addtime_format(self):
        return self.addtime.strftime('%Y-%m-%d %H:%M:%S')

    def save(self):
        super(Profile, self).save()
        data = os.path.join(MEDIA_ROOT, self.avatar.name)
        state = upload_avatar(data)
        if state['success']:
            self.avatar = ImageFieldFile(self, self.avatar, state['path'])

        super(Profile, self).save()  # 再保存一下，包括缩略图等

    def get_user_index_url(self):
        return '/%s/' % self.user.username

    class Meta:
        verbose_name = u'个人'
        verbose_name_plural = u'个人'


class AbstractTweet(models.Model):
    orginmessage = models.ForeignKey(
        'self', verbose_name=u'转发', null=True, blank=True, related_name='ref_set')

    class Meta:
        abstract = True

# Note model


class Tweet(AbstractTweet):

    message = models.TextField(u'消息')
    addtime = models.DateTimeField(u'发布时间', auto_now=True)
    user = models.ForeignKey(User, verbose_name=u'发布者')

    def __unicode__(self):
        return self.message

    def addtime_format_admin(self):
        return self.addtime.strftime('%Y-%m-%d %H:%M:%S')

    def user_name(self):
        return self.user.realname

    class Meta:
        verbose_name = u'消息'
        verbose_name_plural = u'消息'


class Friendship(models.Model):

    fans = models.ForeignKey(
        User,
        related_name='follower_set',
        verbose_name=u'粉丝'
    )

    followers = models.ForeignKey(
        User,
        related_name='fan_set',
        verbose_name=u'关注者'
    )

    def __unicode__(self):
        return u'%s, %s' % (
            self.fans.username,
            self.followers.username
        )

    class Meta:
        unique_together = (('followers', 'fans'), )
        verbose_name = u'朋友'
        verbose_name_plural = u'朋友'


class PrivateMessage(models.Model):

    sender = models.ForeignKey(
        User,
        related_name='receiver_set',
        verbose_name=u'发信人'
    )

    receiver = models.ForeignKey(
        User,
        related_name='sender_set',
        verbose_name=u'收信人'
    )
    privatemsg = models.TextField(
        u'私信', max_length=1000, default='', blank=True)
    isreader = models.IntegerField(u'是否已读', default='0')
    addtime = models.DateTimeField(u'发布时间', auto_now=True)
    
    class Meta:
        verbose_name = u'私信'
        verbose_name_plural = u'私信'

    def message_short(self):
        return formatter.substr(self.privatemsg, 140)

    def addtime_format_admin(self):
        return self.addtime.strftime('%Y-%m-%d %H:%M:%S')

    def __unicode__(self):
        return u'%s, %s' % (
            self.sender.username,
            self.receiver.username
        )

    def get_sender_url(self):
        return '/%s/' % self.sender.username

    def get_receiver_url(self):
        return '/%s/' % self.receiver.username


class Favorite(models.Model):

    favtweet = models.OneToOneField(Tweet, verbose_name=u'收藏微博')

    favuser = models.ManyToManyField(User, verbose_name=u'收藏者')

    addtime = models.DateTimeField(u'收藏时间', auto_now=True)

    def addtime_format_admin(self):
        return self.addtime.strftime('%Y-%m-%d %H:%M:%S')

    class Meta:
        verbose_name = u'收藏'
        verbose_name_plural = u'收藏'

    def __unicode__(self):
        return self.favtweet.user.username


class Reply(models.Model):

    subject = models.ForeignKey(
        Tweet, verbose_name=u'原微博', related_name='replyer_set')

    replyer = models.ForeignKey(
        User, verbose_name=u'回复者', related_name='subject_set')

    replytweet = models.TextField(u'消息')

    addtime = models.DateTimeField(u'回复时间', auto_now=True)

    def addtime_format_admin(self):
        return self.addtime.strftime('%Y-%m-%d %H:%M:%S')

    def __unicode__(self):
        return self.subject.user.username
        
    class Meta:
        verbose_name = u'回复'
        verbose_name_plural = u'回复'